package com.wzl.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzl.backend.mapper.UserMapper;
import com.wzl.backend.pojo.User;
import com.wzl.backend.service.UserService;
import com.wzl.backend.util.FileUtil;
import com.wzl.backend.util.ImageToBase64Util;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper , User> implements UserService {

    @Override
    public boolean addUser(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", user.getEmail());
        List<User> list = this.list(queryWrapper);
        if (list.isEmpty()) {
            user.setRegistTime(new Date(System.currentTimeMillis()));
            long id = IdWorker.getId(user);
            user.setId(id);
            return this.save(user);
        } else {
            return false;
        }
    }

    @Override
    public User login(String username, String password) throws RuntimeException{
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username" , username);
        List<User> list = this.list(queryWrapper);
        if (list.isEmpty()) {
            throw new RuntimeException("用户名不存在");
        }
        for (User user : list) {
            if (user.getPassword().equals(password)) {
                return user;
            }
        }
        throw new RuntimeException("用户密码错误");
    }

    @Override
    public void setUserDefaultIcon(Long id) throws IOException {
        FileUtil.copyIcon("default.png" , id + ".png");
    }

    @Override
    public String getAvatar(Long id) {
        String path = FileUtil.BASE_RESOURCES_PATH;
        path += id + ".png";
        return ImageToBase64Util.convertFileToBase64(path);
    }

    @Override
    public boolean updateAvatar(Long id , String file) {
        String fileName = id + ".png";
        String s = file.split(",")[1];
        ImageToBase64Util.convertBase64ToFile(s , FileUtil.BASE_RESOURCES_PATH , fileName);
        return true;
    }
}
